package com.jsh.action.basic;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.junit.Assert;
import org.springframework.dao.DataAccessException;
import com.jsh.base.BaseAction;
import com.jsh.base.Log;
import com.jsh.model.po.Basicuser;
import com.jsh.model.po.Jira;
import com.jsh.model.po.Logdetails;
import com.jsh.model.vo.basic.JiraModel;
import com.jsh.service.basic.JiraIService;
import com.jsh.service.basic.UserBusinessIService;
import com.jsh.util.PageUtil;

import de.micromata.jira.rest.JiraRestClient;
import de.micromata.jira.rest.core.domain.CommentBean;
import de.micromata.jira.rest.core.domain.ProjectBean;
import de.micromata.jira.rest.core.util.RestException;

@SuppressWarnings("serial")
public class JiraAction extends BaseAction<JiraModel>
{
	private JiraIService jiraService;
	private UserBusinessIService userBusinessService;
	private JiraModel model = new JiraModel();
//	static final String USERNAME_TO_SEARCH = "qianyf1013";//创建者
	static final String ISSUEKEY_TO_SEARCH = "DEMO-1";//问题名
	private String pname = null;//项目名 PROJECT_TO_SEARCH

	static JiraRestClient jiraRestClient;
    public static Long id = (long) 0;
    public static String jname;
    public static String jpassword;
    public static String url;
	private Basicuser sessionUser;
	private String Number;
	public List<ProjectBean> project;
	public Basicuser getSessionUser() {
		return sessionUser;
	}

	public void setSessionUser(Basicuser sessionUser) {
		this.sessionUser = sessionUser;
	}
	public String getPname() {
		return pname;
	}

	public void setPname(String pname) {
		this.pname = pname;
	}
    public String getNumber() {
		return Number;
	}

	public void setNumber(String number) {
		Number = number;
	}
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getBasicData()
	{
		Map<String,List> mapData = model.getShowModel().getMap();
		PageUtil pageUtil = new  PageUtil();
		pageUtil.setPageSize(0);
		pageUtil.setCurPage(0);
		try
		{
			Map<String,Object> condition = pageUtil.getAdvSearch();
			condition.put("sort_s_order", "asc");
			jiraService.find(pageUtil);
			mapData.put("jiraList", pageUtil.getPageList());
		}
		catch (Exception e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>查找系统基础数据信息异常", e);
			model.getShowModel().setMsgTip("exceptoin");
		}
		return SUCCESS;
	}

	/**
	 * 增加
	 * @return
	 */
	public void create()//新用户第一次查看jira数据会创建一个给定的账户密码
	{
		Log.infoFileSync("==================开始调用增加信息方法create()===================");
		Boolean flag = false;
		try
		{
			sessionUser = getUser();
			Jira jira = new Jira();
			jira.setId((long)getUser().getId());
			jira.setJname(model.getJname());
			jira.setJpassword(model.getJpassword());

			jiraService.create(jira);

			//========标识位===========
			flag = true;
			//记录操作日志使用
			tipMsg = "成功";
			tipType = 0;
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>增加信息异常", e);
			flag = false;
			tipMsg = "失败";
			tipType = 1;
		}
		finally
		{
			try
			{
				toClient(flag.toString());
			}
			catch (IOException e)
			{
				Log.errorFileSync(">>>>>>>>>>>>增加信息回写客户端结果异常", e);
			}
		}

		logService.create(new Logdetails(getUser(), "增加", model.getClientIp(),
				new Timestamp(System.currentTimeMillis())
				, tipType, "增加名称为  "+ model.getJname() + " " + tipMsg + "！", "增加" + tipMsg));
		Log.infoFileSync("==================结束调用增加方法create()===================");
	}

	/**
	 * 删除
	 * @return
	 */
	public String delete()
	{
		Log.infoFileSync("====================开始调用删除信息方法delete()================");
		try
		{
			jiraService.delete(model.getJiraID());
			tipMsg = "成功";
			tipType = 0;
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>删除ID为 " + model.getJiraID() + "  的异常", e);
			tipMsg = "失败";
			tipType = 1;
		}
		model.getShowModel().setMsgTip(tipMsg);
		logService.create(new Logdetails(getUser(), "删除", model.getClientIp(),
				new Timestamp(System.currentTimeMillis())
				, tipType, "删除ID为  "+ model.getJiraID() + " " + tipMsg + "！", "删除" + tipMsg));
		Log.infoFileSync("====================结束调用删除信息方法delete()================");
		return SUCCESS;
	}

	/**
	 * 更新
	 * @return
	 */
	public void update()
	{
		Boolean flag = false;
		try
		{
			Jira jira = jiraService.get(model.getJiraID());
			jira.setJname(model.getJname());
			jira.setJpassword(model.getJpassword());
			jiraService.update(jira);

			flag = true;
			tipMsg = "成功";
			tipType = 0;
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>修改ID为 ： " + model.getJiraID() + "信息失败", e);
			flag = false;
			tipMsg = "失败";
			tipType = 1;
		}
		finally
		{
			try
			{
				toClient(flag.toString());
			}
			catch (IOException e)
			{
				Log.errorFileSync(">>>>>>>>>>>>修改回写客户端结果异常", e);
			}
		}
		logService.create(new Logdetails(getUser(), "更新", model.getClientIp(),
				new Timestamp(System.currentTimeMillis())
				, tipType, "更新ID为  "+ model.getJiraID() + " " + tipMsg + "！", "更新" + tipMsg));
	}


	/**
	 * 检查输入名称是否存在
	 */
	public void checkIsNameExist()
	{
		Boolean flag = false;
		try
		{
			flag = jiraService.checkIsNameExist("jname",model.getJname(),"id", model.getJiraID());
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>检查名称为：" + model.getJname() + " ID为： " + model.getJiraID() + " 是否存在异常！");
		}
		finally
		{
			try
			{
				toClient(flag.toString());
			}
			catch (IOException e)
			{
				Log.errorFileSync(">>>>>>>>>>>>回写检查名称为：" + model.getJname() + " ID为： " + model.getJiraID() + " 是否存在异常！",e);
			}
		}
	}

	/**
	 * 查找信息
	 * @return
	 */
	public void findBy()
	{
		try
		{
			PageUtil<Jira> pageUtil = new  PageUtil<Jira>();
			pageUtil.setPageSize(model.getPageSize());
			pageUtil.setCurPage(model.getPageNo());
			pageUtil.setAdvSearch(getCondition());
			jiraService.find(pageUtil);
			List<Jira> dataList = pageUtil.getPageList();

			JSONObject outer = new JSONObject();
			outer.put("total", pageUtil.getTotalCount());
			//存放数据json数组
			JSONArray dataArray = new JSONArray();
			if(null != dataList)
			{
				for(Jira jira:dataList)
				{
					JSONObject item = new JSONObject();
					item.put("id", jira.getId());
					//供应商名称
					item.put("jname", jira.getJname());
					item.put("jpassword", jira.getJpassword());
					item.put("op", 1);
					dataArray.add(item);
				}
			}
			outer.put("rows", dataArray);
			//回写查询结果
			toClient(outer.toString());
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>查找信息异常", e);
		}
		catch (IOException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询信息结果异常", e);
		}
	}
	



	
	public void findjira(){
		try
		{	
			Jira jira = jiraService.findjira((long)getUser().getId());

			JSONObject outer = new JSONObject();
			outer.put("total", 1);
			//存放数据json数组
			JSONArray dataArray = new JSONArray();
			
			JSONObject item = new JSONObject();
			item.put("id", jira.getId());
			item.put("jname", jira.getJname());
			item.put("jpassword", jira.getJpassword());
			item.put("op", 1);
					dataArray.add(item);
		
			outer.put("rows", dataArray);
			//回写查询结果
			toClient(outer.toString());
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>查找信息异常", e);
		}
		catch (IOException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询信息结果异常", e);
		}
	}


	/**
	 * 用户对应显示
	 * @return
	 */
	public void findUserJira()
	{
		try
		{
			PageUtil<Jira> pageUtil = new  PageUtil<Jira>();
			pageUtil.setPageSize(100);
			//pageUtil.setCurPage(model.getPageNo());

			pageUtil.setAdvSearch(getCondition_UserJira());
			jiraService.find(pageUtil);
			List<Jira> dataList = pageUtil.getPageList();

			//开始拼接json数据
			JSONObject outer = new JSONObject();
			outer.put("id", 1);
			outer.put("text", "列表");
			outer.put("state", "open");
			//存放数据json数组
			JSONArray dataArray = new JSONArray();
			if(null != dataList)
			{
				for(Jira jira:dataList)
				{
					JSONObject item = new JSONObject();
					item.put("id", jira.getId());
					item.put("text", jira.getJname());
					//勾选判断1
					Boolean flag = false;
					try
					{
						flag = userBusinessService.checkIsUserBusinessExist("Type",model.getUBType(),"KeyId",model.getUBKeyId(),"Value","["+jira.getId().toString()+"]");
					}
					catch (DataAccessException e)
					{
						Log.errorFileSync(">>>>>>>>>>>>>>>>>设置用户对应的：类型" + model.getUBType() + " KeyId为： " + model.getUBKeyId() + " 存在异常！");
					}
					if (flag==true){item.put("checked", true);}
					//结束
					dataArray.add(item);
				}
			}
			outer.put("children", dataArray);
			//回写查询结果
			toClient("["+outer.toString()+"]");
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>查找异常", e);
		}
		catch (IOException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询结果异常", e);
		}
	}

	/**
	 * 根据用户查找对应列表-仅显示有权限的
	 * @return
	 */
	public void findJiraByUserId(){
		try{
			PageUtil<Jira> pageUtil = new  PageUtil<Jira>();
			pageUtil.setPageSize(0);
			pageUtil.setCurPage(0);
			pageUtil.setAdvSearch(getCondition_UserJira());
			jiraService.find(pageUtil);
			List<Jira> dataList = pageUtil.getPageList();

			//存放数据json数组
			JSONArray dataArray = new JSONArray();
			if(null != dataList)
			{
				for(Jira jira:dataList)
				{
					JSONObject item = new JSONObject();
					//勾选判断1
					Boolean flag = false;
					try
					{
						flag = userBusinessService.checkIsUserBusinessExist("Type",model.getUBType(),"KeyId",model.getUBKeyId(),"Value","["+jira.getId().toString()+"]");
					}
					catch (DataAccessException e)
					{
						Log.errorFileSync(">>>>>>>>>>>>>>>>>查询用户对应的：类型" + model.getUBType() + " KeyId为： " + model.getUBKeyId() + " 存在异常！");
					}
					if (flag==true){
						item.put("id", jira.getId());
						item.put("jname", jira.getJname());
						dataArray.add(item);
					}
				}
			}
			//回写查询结果
			toClient(dataArray.toString());
		}
		catch (DataAccessException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>查找异常", e);
		}
		catch (IOException e)
		{
			Log.errorFileSync(">>>>>>>>>>>>>>>>>>>回写查询结果异常", e);
		}
	}
	
	public void send() throws URISyntaxException, IOException, ExecutionException, InterruptedException, RestException{
		System.out.println(getPname());  
		connect();
		AddCommentToIssue("");
	}
	
	public void sendNumber() throws URISyntaxException, IOException, ExecutionException, InterruptedException, RestException{
		System.out.println("****"+getNumber()+"****");
		sessionUser = getUser();
		Jira jira = jiraService.findjira((long)getUser().getId());
		jname = jira.getJname();
		jpassword = jira.getJpassword();
		connect();
		AddCommentToIssue(getNumber());
	}
	/**
	 * 拼接搜索条件
	 * @return
	 */
	private Map<String,Object> getCondition()
	{
		/**
		 * 拼接搜索条件
		 */
		Map<String,Object> condition = new HashMap<String,Object>();
		condition.put("name_s_like", model.getJname());
//		condition.put("remark_s_like", model.getRemark());
//		condition.put("type_n_eq", model.getType());  
//		condition.put("sort_s_order", "asc");
		return condition;
	}

	/**
	 * 拼接搜索条件
	 * @return
	 */
	private Map<String,Object> getConditionByType()
	{
		/**
		 * 拼接搜索条件
		 */
		Map<String,Object> condition = new HashMap<String,Object>();
//		condition.put("type_n_eq", model.getType());  
		condition.put("sort_s_order", "asc");
		return condition;
	}

	/**
	 * 拼接搜索条件
	 * @return
	 */
	private Map<String,Object> getCondition_UserJira()
	{
		/**
		 * 拼接搜索条件
		 */
		Map<String,Object> condition = new HashMap<String,Object>();
		condition.put("type_n_eq", 0);
		condition.put("sort_s_order", "asc");
		return condition;
	}
	


	//=============以下spring注入以及Model驱动公共方法，与Action处理无关==================
	@Override
	public JiraModel getModel()
	{
		return model;
	}
	public void setJiraService(JiraIService jiraService)
	{
		this.jiraService = jiraService;
	}

	public void setUserBusinessService(UserBusinessIService userBusinessService) {
		this.userBusinessService = userBusinessService;
	}
	
	public void connect() throws URISyntaxException, IOException, ExecutionException, InterruptedException {
        ExecutorService	executorService	= Executors.newFixedThreadPool(100);
//        ProxyHost proxy = new ProxyHost("proxy", 3128);
        URI uri = new URI(url);
        jiraRestClient = new JiraRestClient(executorService);
        jiraRestClient.connect(uri, jname, jpassword);
    }
    public void AddCommentToIssue(String message) throws URISyntaxException, IOException, RestException {
        CommentBean commentBean = new CommentBean();
        if(message == ""){
        	commentBean.setBody("This is a new comment via JiraRestClient.");
        }
        else{
        	commentBean.setBody("单号"+message+"正在向您催单，请您尽快发货!");	
        }
        boolean commentToIssue = jiraRestClient.getIssueClient().addCommentToIssue(ISSUEKEY_TO_SEARCH, commentBean);
//        Assert.assertTrue(commentToIssue);
        System.out.println("发送成功");
    }
//从jira获取到所有的项目名称    
    public void testGetAllProjects() throws RestException, IOException, ExecutionException, InterruptedException {
    	Future<List<ProjectBean>> future = jiraRestClient.getProjectClient().getAllProjects();
        project = future.get();
    }
//将获取到的项目名传给页面    
    public void go() throws URISyntaxException, IOException, ExecutionException, InterruptedException, RestException{
		Jira jira = jiraService.findjira((long)getUser().getId());
    	jname = jira.getJname();
		jpassword = jira.getJpassword();
		connect();
		testGetAllProjects();
		//回写查询结果 
		toClient(project+"");
    }
//读取文件内的url
    static{
    	InputStream in = null;
		try{
			Properties properties = new Properties();
			in = JiraAction.class.getClassLoader().getResourceAsStream("jira.properties");
			properties.load(in);
			url = properties.getProperty("url");
			System.out.println("读取配置信息成功！");

		}catch(Exception e){
			e.printStackTrace();
			System.out.println("读取配置信息失败！");

		}finally{
			if(in != null){
				try{
					in.close();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		}
    }

}
